var settings = new Object();

$(function()
{
	// start updating the temperature/time/mode displayed periodically
	updateStatus();
	// refresh the current settings displayed in the UI
	getSettings();
});

function updateStatus()
{
	$.ajax(
	{
		url: "/getStatus.cgi?" + Math.random(),
		type: "GET",
		data: "",
		dataType: "json",
		contentType: "application/json",
		timeout: 15000,
		success: function(result)
		{
			if (result.result == "success")
			{
				$('#curTemp').text(result.temperature);
				$('#curOpMode').text("( " + result.hvacMode + " )");
            	$('#curSetTemp').text(result.setTemp == 0 ? "---" : result.setTemp);
				$('#curTimeInfo').text(result.time);
				$('#acRuntimeHr').val(Math.floor(result.ACRuntime / 360));
				$('#acRuntimeMin').val(Math.floor(result.ACRuntime / 60));
				$('#heatRuntimeHr').val(Math.floor(result.HeatRuntime / 360));
				$('#heatRuntimeMin').val(Math.floor(result.HeatRuntime / 60));
				$('#fanRuntimeHr').val(Math.floor(result.FanRuntime / 360));
				$('#fanRuntimeMin').val(Math.floor(result.FanRuntime / 60));
			}
            setTimeout('updateStatus()', 15000);
		},
		error: function(request, textStatus, errorThrown)
		{
            setTimeout('updateStatus()', 15000);
		}
	});
}

function getSettings()
{
	$.ajax(
	{
		url: "/getSettings.cgi?" + Math.random(),
		type: "GET",
		data: "",
		dataType: "json",
		contentType: "application/json",
		timeout: 60000,
		beforeSend: function() 
		{ 
			$.blockUI ({ message: '<p style="font-weight:bold"><img src="images/busy.gif" /> Retrieving settings...</p>' });
		},
		success: function(result)
		{
			$.unblockUI();
			if (result.result == "success")
				updateSettings(result);
			else
				$('#settingsNotLoaded').dialog('open');
		},
		error: function(request, textStatus, errorThrown)
		{
			$.unblockUI();
			$('#settingsNotLoaded').dialog('open');
		}
	});
}

var days = new Array(
	"#sunScheduleList",
	"#monScheduleList",
	"#tuesScheduleList",
	"#wedScheduleList",
	"#thursScheduleList",
	"#friScheduleList",
	"#satScheduleList");

function updateSettings(loadedSettings)
{
	settings = loadedSettings;
	
	$('#macAddr1').val(settings.macAddr1);
	$('#macAddr2').val(settings.macAddr2);
	$('#macAddr3').val(settings.macAddr3);
	$('#macAddr4').val(settings.macAddr4);
	$('#macAddr5').val(settings.macAddr5);
	$('#macAddr6').val(settings.macAddr6);
	$('input[name="dhcpEnabled"][value="' + settings.dhcpEnabled + '"]').attr('checked', 'checked');
	$('#ipAddr1').val(settings.ipAddr1);
	$('#ipAddr2').val(settings.ipAddr2);
	$('#ipAddr3').val(settings.ipAddr3);
	$('#ipAddr4').val(settings.ipAddr4);
	$('#inetMask1').val(settings.inetMask1);
	$('#inetMask2').val(settings.inetMask2);
	$('#inetMask3').val(settings.inetMask3);
	$('#inetMask4').val(settings.inetMask4);
	$('#gatewayAddr1').val(settings.gatewayAddr1);
	$('#gatewayAddr2').val(settings.gatewayAddr2);
	$('#gatewayAddr3').val(settings.gatewayAddr3);
	$('#gatewayAddr4').val(settings.gatewayAddr4);
	$('#DNSAddr1').val(settings.dnsAddr1);
	$('#DNSAddr2').val(settings.dnsAddr2);
	$('#DNSAddr3').val(settings.dnsAddr3);
	$('#DNSAddr4').val(settings.dnsAddr4);
	$('#ssid').val(settings.ssid);
	$('#wepKey').val(settings.wepKey);

	$('#manual_amount').val(settings.manualTemp);
	$('#manual_slider').attr('value', settings.manualTemp);
	$('#var_amount').val(settings.tempVariance);
	$('#var_slider').attr('value', settings.tempVariance);
	$('#setHVACMode').text(settings.setHVACMode);
	$('input[name="setHVACMode"][value="' + settings.setHVACMode + '"]').attr('checked', 'checked');
	$('#setFanMode').text(settings.setFanMode);
	$('input[name="setFanMode"][value="' + settings.setFanMode + '"]').attr('checked', 'checked');
	$('input[name="myHeaterType"][value="' + settings.myHeaterType + '"]').attr('checked', 'checked');
	//$('input[name="tempUnit"][value="' + settings.tempUnit + '"]').attr('checked', 'checked');
	$('.units').each(function() { $(this).html("&deg;" + settings.tempUnit); });
	$('#opMode').text(settings.opMode);
	$('input[name="opMode"][value="' + settings.opMode + '"]').attr('checked', 'checked');
	$('#poll_amount').val(settings.pollInterval);
	$('#poll_slider').attr('value', settings.pollInterval);
	$('#tempOffset').val(settings.tempOffset);
	$('#autoTimeSync').attr('checked', settings.autoTimeSync ? 'checked' : 'unchecked');
	$('#useDaylightSavings').attr('checked', settings.daylightSavingEnabled ? 'checked' : 'unchecked');
	$('#timeServerField').val(settings.timeServerAddress);
	$('#timeZone').val(settings.timeZone);
	
	for (var i = 0; i < days.length; i++)
	{
		$(days[i]).empty();
		for (var j = 0; j < settings.schedule[i].length; j++)
		{
			var hours = Math.floor(settings.schedule[i][j].time / 60);
			var min = settings.schedule[i][j].time % 60;
			var am_pm = "AM";

			if (hours == 0)
				hours = 12;
			else if (hours > 12)
			{
				hours -= 12;
				am_pm = "PM";
			}

			addToSchedule(
				days[i], hours + ":" + (min < 10 ? "0" : "") + min + " " + am_pm,
				settings.schedule[i][j].temp);
		}
	}
}

var newSettings;
function saveSettings(saveScheduleAfter)
{
	newSettings = new Object();

	newSettings.macAddr1 = $('#macAddr1').val();
	newSettings.macAddr2 = $('#macAddr2').val();
	newSettings.macAddr3 = $('#macAddr3').val();
	newSettings.macAddr4 = $('#macAddr4').val();
	newSettings.macAddr5 = $('#macAddr5').val();
	newSettings.macAddr6 = $('#macAddr6').val();
	newSettings.dhcpEnabled = $('input[name="dhcpEnabled"]:checked').val();
	newSettings.ipAddr1 = $('#ipAddr1').val();
	newSettings.ipAddr2 = $('#ipAddr2').val();
	newSettings.ipAddr3 = $('#ipAddr3').val();
	newSettings.ipAddr4 = $('#ipAddr4').val();
	newSettings.inetMask1 = $('#inetMask1').val();
	newSettings.inetMask2 = $('#inetMask2').val();
	newSettings.inetMask3 = $('#inetMask3').val();
	newSettings.inetMask4 = $('#inetMask4').val();
	newSettings.gatewayAddr1 = $('#gatewayAddr1').val();
	newSettings.gatewayAddr2 = $('#gatewayAddr2').val();
	newSettings.gatewayAddr3 = $('#gatewayAddr3').val();
	newSettings.gatewayAddr4 = $('#gatewayAddr4').val();
	newSettings.dnsAddr1 = $('#DNSAddr1').val();
	newSettings.dnsAddr2 = $('#DNSAddr2').val();
	newSettings.dnsAddr3 = $('#DNSAddr3').val();
	newSettings.dnsAddr4 = $('#DNSAddr4').val();
	newSettings.ssid = $('#ssid').val();
	newSettings.wepKey = $('#wepKey').val();

	newSettings.manualTemp = $('#manual_amount').val();
	newSettings.tempVariance = $('#var_amount').val();
	newSettings.setHVACMode = $('input[name="setHVACMode"]:checked').val();
	newSettings.setFanMode = $('input[name="setFanMode"]:checked').val();
	newSettings.myHeaterType = $('input[name="myHeaterType"]:checked').val();
	//newSettings.tempUnit = $('input[name="tempUnit"]:checked').val();
	newSettings.tempUnit = "F";
	newSettings.opMode = $('input[name="opMode"]:checked').val();
	newSettings.pollInterval = $('#poll_amount').val();
	newSettings.tempOffset = $('#tempOffset').val();
	newSettings.autoTimeSync = $('#autoTimeSync').attr('checked');
	newSettings.daylightSavingEnabled = $('#useDaylightSavings').attr('checked');
	newSettings.timeServerAddress = $('#timeServerField').val();
	newSettings.timeZone = $('#timeZone').val();

	$.ajax(
	{
		url: "/saveSettings.cgi?" + Math.random(),
		type: "POST",
		data: JSON.stringify(newSettings),
		processData: false,
		dataType: "json",
		contentType: "application/json",
		timeout: 60000,
		beforeSend: function() 
		{ 
			$.blockUI ({ message: '<p style="font-weight:bold"><img src="images/busy.gif" /> Saving settings...</p>' });
		},
		success: function(result)
		{
			$.unblockUI();
			if (result.result == "success")
			{
				var oldSettings = settings;
				settings = newSettings;
				settings.schedule = oldSettings.schedule;
				$('#setHVACMode').text(settings.setHVACMode);
				$('#setFanMode').text(settings.setFanMode);
				$('#opMode').text(settings.opMode);
				$('#curSetTemp').text(settings.manualTemp == 0 ? "---" : settings.manualTemp);
				if (saveScheduleAfter)
				{
					saveSchedule();
				}
				else
				{
					$('#settingsSaved').dialog('open');
				}
			}
			else
			{
				$('#settingsNotSaved').dialog('open');
			}
		},
		error: function(request, textStatus, errorThrown)
		{
			$.unblockUI();
			$('#settingsNotSaved').dialog('open');
		}
	});
}

function saveSchedule()
{
	newSettings = new Object();

	newSettings.schedule = new Array();

	for (var i = 0; i < days.length; i++)
	{
		newSettings.schedule[i] = new Array();
		for (var j = 0; j < $(days[i] + '>li').length; j++)
		{
			var item = new Object();
			item.temp = $(days[i] + '>li:nth-child(' + (j+1) + ')>.temp').text();
			item.time = $(days[i] + '>li:nth-child(' + (j+1) + ')>.hiddenTime').text();
			newSettings.schedule[i][j] = item;
		}
	}

	$.ajax(
	{
		url: "/saveSchedule.cgi?" + Math.random(),
		type: "POST",
		data: JSON.stringify(newSettings),
		processData: false,
		dataType: "json",
		contentType: "application/json",
		timeout: 60000,
		beforeSend: function() 
		{ 
			$.blockUI ({ message: '<p style="font-weight:bold"><img src="images/busy.gif" /> Saving schedule...</p>' });
		},
		success: function(result)
		{
			$.unblockUI();	
			if (result.result == "success")
			{
				settings.schedule = newSettings.schedule;
				$('#curSetTemp').text(settings.manualTemp == 0 ? "---" : settings.manualTemp);
				$('#settingsSaved').dialog('open');
			}
			else
			{
				$('#settingsNotSaved').dialog('open');
			}
		},
		error: function(request, textStatus, errorThrown)
		{
			$.unblockUI();
			$('#settingsNotSaved').dialog('open');
		}
	});
}
